package com.siashan.unipay4j.ali.redpack;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.siashan.unipay4j.ali.AbstractAliPay;
import com.siashan.unipay4j.ali.AliConstants;
import com.siashan.unipay4j.ali.transfer.AliTransferState;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.redpack.*;
import com.siashan.unipay4j.core.util.EnumUtil;
import com.siashan.unipay4j.core.util.StrUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝红包查询
 *
 * @author siashan
 * @since v1.0.1
 **/
public class AliPayRedpackQuery extends AbstractAliPay implements IRedpackQuery {


    /**
     * 查询红包发放记录
     *
     * @param model   红包查询实体
     * @return 红包发放记录
     */
    @Override
    public Result<RedpackQueryResponse> execQuery(RedpackQueryModel model) {
        AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
        request.setBizContent(JSON.toJSONString(wrapParam(model)));
        try {
            AlipayFundTransOrderQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                return Result.tradeSuccess(wrapResponse(response));
            } else {
                return Result.tradeFail(response.getSubCode(), response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return Result.exception();
    }

    /**
     * 包装转账结果
     *
     * @param r  支付宝转账结果
     * @return  转账结果
     */
    private RedpackQueryResponse wrapResponse(AlipayFundTransOrderQueryResponse r) {
        AliTransferState transferState = EnumUtil.getIEnum(AliTransferState.class, r.getStatus());
        RedpackQueryResponse response = new RedpackQueryResponse();
//        response.setState(transferState.getTransferState());
        response.setOutTradeNo(r.getOutBizNo());
        response.setTradeNo(r.getOrderId());
        response.setBody(JSON.toJSONString(r));
        return response;
    }


    /**
     * 包装查询参数
     *
     * @param model 查询实体
     * @return  查询参数
     */
    private Map<String, String> wrapParam(RedpackQueryModel model) {
        Map<String, String> param = new HashMap<>();
        if (StrUtil.isNotEmpty(model.getOutTradeNo())) {
            param.put("out_biz_no", model.getOutTradeNo());
        }
        param.put("product_code", AliConstants.ProductCode.STD_RED_PACKET );
        param.put("biz_scene", AliConstants.BizScene.DIRECT_TRANSFER );

        return param;
    }
}
